<!--
 * @Description: 表单页内容
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-08-02 16:52:18
 * @LastEditTime: 2022-12-10 15:01:14
 * @FilePath: \cscec-pms-admin\src\views\design\training\trainingConference\components\AddConference.vue
-->
<template>
  <a-spin :spinning="loading">
    <a-card>
      <title-name title="会议发起" />
      <custom-form
        ref="form"
        :is-validate="true"
        :edit-model="''"
        :rules="rules"
        :form="form"
        :form-list="formOption"
        @selectOrg="selectOrg"
        @getProjectInfo="getProjectInfo"
      >
        <template slot="speakerId">
<!--          // 特殊处理-->
          <div v-if="pageName === 'trainingConference'">
            <selectPerson
                    show-search
                    v-model="form.speakerId"
                    @personChanged="personChanged"
            ></selectPerson>
          </div>
          <SelectPersonByProject
                  v-else
            :id="form.branchComId"
            v-model="form.speakerId"
            :project-id="form.projectId"
            :show-search="true"
            :is-continue="isContinue"
            mode="combobox"
            placeholder="请选择"
            option-label-prop="children"
          />
        </template>
        <template slot="meetingTime">
          <a-date-picker
            v-model="form.meetingTime"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择"
          />
        </template>
      </custom-form>
    </a-card>
    <a-card>
      <title-name title="参会人员" />
      <a-form-model-item
        label="参会者选择："
        prop="meetingEmployeeDTOList"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <!-- 操作 -->
        <div class="mb12">
          <a-button
            icon="plus"
            class="btn_right"
            type="primary"
            @click="visible = true"
          >
            添加人员
          </a-button>
          <a-button
            icon="delete"
            type="danger"
            :disabled="form.employeeList.length < 1"
            @click="handleRemoveMore"
          >
            移除
          </a-button>
        </div>
        <!-- 操作 -->
        <!-- 统计选中项 -->
        <a-alert :show-icon="true">
          <template slot="message">
            <span style="margin-right: 12px">
              已选择:
              <a>
                <b>{{ selectedRowKeys.length }}</b>
              </a>
              项
            </span>
          </template>
        </a-alert>
        <!-- 统计选中项 -->
        <!-- 表格 -->
        <s-table
          ref="tableEmployee"
          table-layout="fixed"
          size="default"
          row-key="id"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :row-selection="rowSelection"
          show-size-changer
          show-quick-jumper
          show-pagination="auto"
        >
          <span
            slot="actions"
            slot-scope="text, record, index"
          >
            <template>
              <a @click="handleRemove(index)">移除</a>
            </template>
          </span>
        </s-table>
        <!-- 表格 -->
      </a-form-model-item>
    </a-card>
    <div class="tool-btns page-btn-right-top">
      <a-button
        class="ml20"
        :loading="submitLoading"
        type="primary"
        @click="handleSubmit"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <!-- 添加人员模态框 -->
    <dialog-edit
      ref="dialogEdit"
      :meeting-employee-d-t-o-list-data="form.employeeList"
      :visible.sync="visible"
      @confirm="addEmployee"
      @confirms="addEmployees"
    />
    <!-- 添加人员模态框 -->
    <!-- <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover> -->
  </a-spin>
</template>
<script>
import { trainType, columnsEmployee, meetingTypeNameText, meetingTypeNumber, btnPermission } from './model.js'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import dialogEdit from '@/views/conference/standardConference/conferenceList/dialogEdit.vue'
import training from '@/api/design/training'
import selectPerson from './selectPerson'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
export default {
  name: 'AddConference',
  components: {
    dialogEdit,
    SelectPersonByProject,
    selectPerson
  },
  data() {
    return {
      // 页面加载
      loading: false,
      // 表单
      form: {
        meetingTypeName: meetingTypeNameText[this.$route.query.pageName],
        employeeList: [],
        projectDesignType: '',
        middleId: '',
        projectId: ''
      },
      // 表格选中项
      selectedRowKeys: [],
      // 表格复选
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys) => {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      // 表头
      columns: columnsEmployee,
      // 添加人员模态框显示隐藏
      visible: false,
      // 提交loading
      submitLoading: false,
      // 项目设计管理类别
      designType: {},
      // 按钮权限
      btnPermission,
      pageName:this.$route.query.pageName,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      // 继续 主持人/主讲人 接口
      isContinue: false
    }
  },
  computed: {
    // 表单配置
    formOption() {
      console.log(this.$route.query.pageName === 'trainingConference', '2222')
      const option1 = [
        {
          label: '会议类型',
          keyName: 'meetingTypeName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: this.$route.query.pageName === 'trainingConference' ? 'middleId': 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true,
          needTags: this.$route.query.pageName === 'trainingConference' ? ['PD', 'CO', 'BC'] : ['BC','PD'],
          isAllowNnect: this.$route.query.pageName === 'trainingConference',
          checkStrictly: this.$route.query.pageName !== 'trainingConference',
          isQueryProjecDetail: this.$route.query.pageName !== 'trainingConference',
        },
        // {
        //   label: '所属分公司',
        //   keyName: 'branchComId',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: true
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // },
        // {
        //   label: '所属项目',
        //   keyName: 'projectId',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: true,
        //     keyValue: 'branchComId',
        //     isEdit: true,
        //     form: this.form
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // }
      ]
      const option2 = [
        {
          label: '会议名称',
          keyName: 'meetingName',
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '主持人/主讲人',
          keyName: 'speakerId',
          slot: true,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '会议时间',
          keyName: 'meetingTime',
          slot: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        }
      ]
      const option3 = [
        {
          label: '会议地点',
          keyName: 'meetingPlace',
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '会议说明',
          keyName: 'meetingExplain',
          type: 'BaseTextarea',
          attrs: {
            maxLength: 1000
          },
          rules: [{ required: true, message: '请输入', trigger: 'change' }],
          span: 24
        }
      ]
      let list = []
      switch (this.$route.query.pageName) {
        // 设计培训管理会
        case 'trainingConference':
          list = list.concat(
            option1,
            [
              {
                label: '培训分类',
                keyName: 'trainType',
                type: 'a-select',
                data: trainType,
                rules: [{ required: true, message: '请选择', trigger: 'change' }]
              }
            ],
            option2,
            option3
          )
          break
        // 设计策划联合评审会
        case 'planningJoint':
          list = list.concat(
            option1,
            [
              {
                label: '项目设计管理类别',
                keyName: 'projectDesignType',
                type: 'BaseInput',
                rules: [{ required: true, message: '请选择', trigger: 'change' }],
                disabled: true
              }
            ],
            option2,
            option3
          )
          break
        // 设计策划启动会
        case 'planningStart':
          list = list.concat(
            option1,
            [
              {
                label: '项目设计管理类别',
                keyName: 'projectDesignType',
                type: 'BaseInput',
                rules: [{ required: true, message: '请选择', trigger: 'change' }],
                disabled: true
              }
            ],
            option2,
            option3
          )
          break
        // 设计管理复盘会
        case 'analyseConference':
          list = list.concat(option1, option2, option3)
          break
      }
      return list
    },
    // 校验
    rules() {
      const obj = {}
      this.formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
  watch: {
    // 'form.projectId': {
    //   handler(val) {
    //     this.getDesignType(val)
    //   }
    // },
    pageName:{
      async handler(val) {
        //获取通过获取流程配置值
         let config = val == 'trainingConference'? 'design_training_management':'design_management_review';
         this.processConfig = await this.$getConfigFn(config)
      },
      immediate: true
    }
  },
  methods: {
    personChanged(val) {
      this.form.speaker = val.name
    },
    selectOrg(val) {
      // 3级权限 策划书页面单独处理
      if(this.$route.query.pageName === 'trainingConference') {
        if(val.length>2){
          this.isContinue = true
          this.form.branchComId = val[val.length - 2].orgId
          this.form.projectId = val[val.length - 1].projectId
        }else{
          this.isContinue = true
          this.form.branchComId = val[val.length - 1].orgId
          this.form.projectId = null
        }
      } else {
        if(val.length>1){
          this.isContinue = true
          this.form.branchComId = val[val.length - 2].orgId
          this.form.projectId = val[val.length - 1].projectId
        }else{
          this.isContinue = true
          this.form.branchComId = val[val.length - 1].orgId
        }
      }
    console.log(this.form, '111111111111111')
    },
    getProjectInfo(info) {
      this.form.projectDesignType = info.designName
      this.$forceUpdate()
    },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    loadData(parameter) {
      const vm = this
      try {
        return new Promise((resolve, reject) => {
          let obj = {}
          obj.currentPage = parameter.pageNo
          obj.pageSize = parameter.pageSize
          obj.totalPage = Math.ceil(vm.form.employeeList.length / parameter.pageSize)
          obj.totalSize = vm.form.employeeList.length
          obj.data = vm.form.employeeList || []
          resolve(obj)
        })
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 获取项目设计管理类别
     * @param {*}
     * @return {*}
     */
    async getDesignType(val) {
      try {
        const { data } = await getAuditProject({
          projectId: val,
          branchComIds: [this.form.branchComId]
        })
        this.designType = {
          designTypeId: data[0]?.designTypeId || undefined,
          designTypeName: data[0]?.designTypeName || undefined
        }
        this.form.projectDesignType = this.designType.designTypeName
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 人员表单单个添加
     * @param {object} e 人员
     * @return {Void}
     */
    addEmployee(e) {
      this.form.employeeList.push(e)
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 人员表单多个添加
     * @param {array} e 人员列表
     * @return {Void}
     */
    addEmployees(e) {
      e.forEach((item) => {
        this.form.employeeList.push(item)
      })
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 移除人员选中项
     * @param {void}
     * @return {void}
     */
    handleRemoveMore() {
      // 若有选中项
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定移除这些数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          for (let index = 0; index < that.form.employeeList.length; index++) {
            let item = that.form.employeeList[index]
            if (that.selectedRowKeys.includes(item.id)) {
              that.form.employeeList.splice(index, 1)
              index--
            }
          }
          that.$refs.tableEmployee.clearSelected()
          that.$refs.tableEmployee.refresh(true)
        }
      })
    },
    /**
     * @description: 移除人员
     * @param {number} index
     * @return {void}
     */
    handleRemove(index) {
      this.form.employeeList.splice(index, 1)
      this.$refs.tableEmployee.refresh(true)
    },
    /**
     * @description: 提交
     * @param {void}
     * @return {void}
     */
    handleSubmit() {
      this.setProcessConfig = null;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              return
            }
          if (this.$route.query.pageName === 'planningJoint') {
            if (
              this.form.projectDesignType === 'A1类' ||
              this.form.projectDesignType === 'A2类' ||
              this.form.projectDesignType === 'A3类'
            ) {
              if (this.form.employeeList.length > 0) {
                this.submitLoading = true
                const form = this.$clone(this.form)
                form.employeeList = form.employeeList.map((el) => {
                  return {
                    userId: el.userId
                  }
                })
                form.meetingType = meetingTypeNumber[this.$route.query.pageName]
                form.meetingTime = form.meetingTime.format('YYYY-MM-DD HH:mm')
                training
                  .insertSelective(form)
                  .then((res) => {
                    if (res.code === 200) {
                      this.$message.success('新增成功')
                      this.handleClose()
                        //提交时，返回id
                      this.businessId = res.data.id;
                      this.setProcessConfig = this.processConfig;
                    } else {
                      this.$message.warning(res.message)
                    }
                  })
                  .finally(() => {
                    this.submitLoading = false
                  })
              } else {
                this.$message.warning('请选择参会人员')
              }
            } else {
              this.$message.warning('该项目不为a类项目，不能进行设计策划联合评审会')
            }
          } else {
            if (this.form.employeeList.length > 0) {
              this.submitLoading = true
              const form = this.$clone(this.form)
              form.employeeList = form.employeeList.map((el) => {
                return {
                  userId: el.userId
                }
              })
              form.meetingType = meetingTypeNumber[this.$route.query.pageName]
              form.meetingTime = form.meetingTime.format('YYYY-MM-DD HH:mm')
              if(!form.projectId) {
                if(this.$userInfo().currentPost.tagCode !='PD') {
                  form.projectId = ''
                }
              }
              training
                .insertSelective(form)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success('新增成功')
                    //提交时，返回id
                    this.handleClose()
                    this.businessId = res.data.id;
                    this.setProcessConfig = this.processConfig;
                  } else {
                    this.$message.warning(res.message)
                  }
                })
                .finally(() => {
                  this.submitLoading = false
                })
            } else {
              this.$message.warning('请选择参会人员')
            }
          }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     * @description: 关闭
     * @param {void}
     * @return {void}
     */
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
